#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>

#define UART_DEVICE "/dev/ttyCH9344USB3"

int main() {
    int fd;
    struct termios new_cfg;
    speed_t speed = B115200;

    // 打开串口（阻塞模式）
    fd = open(UART_DEVICE, O_RDWR | O_NOCTTY);
    if (fd < 0) {
        perror("Failed to open UART");
        return -1;
    }

    // 配置串口
    if (tcgetattr(fd, &new_cfg) != 0) {
        perror("tcgetattr");
        close(fd);
        return -1;
    }

    cfmakeraw(&new_cfg);
    cfsetspeed(&new_cfg, speed);
    new_cfg.c_cflag |= CREAD | CLOCAL; // CLOCAL: 忽略 modem 控制线
    new_cfg.c_cflag &= ~CSIZE;
    new_cfg.c_cflag |= CS8;
    new_cfg.c_cflag &= ~PARENB;
    new_cfg.c_cflag &= ~CSTOPB;
    new_cfg.c_cc[VMIN] = 1;   // 至少1字节
    new_cfg.c_cc[VTIME] = 5;  // 0.5秒超时

    if (tcsetattr(fd, TCSANOW, &new_cfg) != 0) {
        perror("tcsetattr");
        close(fd);
        return -1;
    }

    // 清空缓冲区
    tcflush(fd, TCIOFLUSH);

    char buff[256];
    ssize_t ret;
    while (1) {
        ret = read(fd, buff, sizeof(buff) - 1);
        if (ret > 0) {
            buff[ret] = '\0';
            printf("Received (%zd bytes): %s\n", ret, buff);

            // 回显原始字节（不是 strlen！）
            write(fd, buff, ret);
            printf("Echoed back.\n");
            printf("$(date): 422-2 测试成功\n");
            system("echo \"$(date): 422-2 测试成功\" >> /userfs/all.txt");
        } else if (ret == 0) {
            // 串口无数据（理论上不会发生）
            usleep(10000); // 10ms
        } else {
            perror("read");
            break;
        }
    }

    close(fd);
    return 0;
}